package com.laborer.PTSS.web.servlet;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.laborer.PTSS.domain.ResultInfo;
import com.laborer.PTSS.domain.User;
import com.laborer.PTSS.service.UserService;
import com.laborer.PTSS.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * Created by fei on 2019/11/23.
 */
@WebServlet("/user/*")  // /user/add  /user/find
public class UserServlet extends BaseServlet {
    // 声明一个UserService的业务对象
    private UserService service = new UserServiceImpl();

    /**
     * 注册功能
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 验证码校验，先验证验证码是否正确，如果验证码正确，再做下面所有的逻辑操作
        // 如果验证码不正确，后面的操作就不用做了
        String check = request.getParameter("check");
        // 从session中获取验证码
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");// 为了保证验证码只能使用一次
        // 比较
        if (checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)) {
            // 验证码错误
            ResultInfo info = new ResultInfo();
            // 注册失败
            info.setFlag(false);
            info.setErrorMsg("Invalid verification code!");
            // 将info对象序列化为json
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(info);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return;
        }

        // 1.获取数据
        Map<String, String[]> map = request.getParameterMap();
        // 2.封装对象
        User user = new User();
        try {
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        // 3.调用service完成注册
        //UserService service = new UserServiceImpl();
        // ************
        boolean flag = service.regist(user);
        ResultInfo info = new ResultInfo();
        // 4.响应结果
        if (flag) {
            // 注册成功
            info.setFlag(true);
        } else {
            // 注册失败
            info.setFlag(false);
            info.setErrorMsg("Fail to register！Please contact the administrator.");
        }

        // 将info对象序列化为json
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(info);

        // 将json数据写回客户端
        // 设置content-type
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }

    /**
     * 登录功能
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.获取用户名和密码数据
        Map<String, String[]> map = request.getParameterMap();
        // 2.封装User对象
        User user = new User();

        try {
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        // 3.调用Service查询
        //UserService service = new UserServiceImpl();
        User u = service.login(user);
        ResultInfo info = new ResultInfo();

        // 4.判断用户对象是否为null
        if (u == null) {
            // 用户名或密码错误
            info.setFlag(false);
            info.setErrorMsg("Invalid username or password");
        }

        // 6.判断登录成功
        else {
            // //将用户信息放入HttpSession中
            request.getSession().setAttribute("user", u);//登录成功标记
            // 登录成功
            info.setFlag(true);
        }
        if (info.isFlag()) {
            JSONObject jo = new JSONObject();
            jo.put("flag", true);
            jo.put("username", user.getUsername());
            writeValue(jo, response);
            return;
        }
        // 响应数据
        /*ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        mapper.writeValue(response.getOutputStream(),info);*/
        writeValue(info, response);
    }

    /**
     * 查询单个对象
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void findOne(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 从session中获取登录用户
        Object user = request.getSession().getAttribute("user");
        if (user == null) {
            User _user = new User();
            writeValue(_user, response);
        }
        writeValue(user, response);
    }

    public void getUserByUsername(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("un");
        User user = service.getUserByUsername(username);
        JSONObject jo = new JSONObject();
        jo.put("firstname", user.getFirstname());
        jo.put("lastname", user.getLastname());
        jo.put("username", user.getUsername());
        writeValue(jo, response);
    }

    /**
     * 退出功能
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.销毁session
        request.getSession().invalidate();

        // 2.跳转页面
        response.sendRedirect(request.getContextPath() + "/login.html");

    }
}
